var layer = layui.layer //弹层
    ,table = layui.table //表格
form = layui.form,$ = layui.jquery,changeList=[],laydate = layui.laydate,indexs = 0,checkboxs =false;
lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});

function getAllJson(jsons) {
    let tmpitem = []
    for (let item of jsons) {
        let tmparr = {}
        tmparr["value"] = item["code"];
        tmparr["name"] = item["name"];
        tmparr.selected=true;
        if (item["users"]) {
            for (let it of item["users"]) {
                item["list"].push(it)
            }
        }
        if (item["list"] && item["list"].length) {
            tmparr["children"] = getAllJson(item["list"]);
            tmpitem.push(tmparr)
        } else {
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getxmselect(el, name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon: true,
            indent: 20,
            expandedKeys: false
        },
        height: 'auto',
        data: data,
        on: function ({arr, change, isAdd}) {
            return this
        }
    })
}
let deptSalesmanList=[];
layer.ready(function () {
    //获取当前用户所属部门树()
    let currentDeptTreeList = getAllUserDepartmentTree();
    if (currentDeptTreeList && currentDeptTreeList.list) {
        let deptTree = getAllJson(currentDeptTreeList.list);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", deptTree);
    } else {
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
    }

});
form.render();//表单刷新

table.render({
    elem: '#mains'
    ,data:[]
    ,cols: [[
        {checkbox: true, sort : true,title:'选择'},
        {field:'billNo', title:'合同编号',sort:true}
        ,{field:'customerCode', title:'客户合同号',sort:true}
        ,{field:'customerName', title:'客户名称',sort:true}
        ,{field:'signingDate', title:'签约日期',sort:true}
        // ,{field:'leadTime', title:'备货期限',sort:true}
        ,{field:'priceTermsName', title:'价格术语',sort:true}
        ,{field:'carryTime', title:'出运日期',sort:true}
        ,{field:'modeOfTransport', title:'运输方式',sort:true}
        ,{field:'currency', title:'币种',sort:true}
        ,{field:'salesmanCode',hide:true}
        ,{field:'salesmanName', title:'业务员',sort:true}
        ,{field:'businessModelName', title:'业务模式',sort:true}
    ]]
    ,id: 'mainstableid'
    ,height: 300
    ,page: true
    ,done: function (res, curr, count) {
        table.render({
            elem: '#product'
            ,data:[]
            ,cols: [[
                {checkbox: true, sort : true,title:'选择'}
                ,{field:'productCode', title:'产品编码', sort : true}
                ,{field:'specificationCode', title:'规格编码', sort : true}
                ,{field:'specificationExplanation', title:'规格说明', sort : true}
                ,{field: 'clientProductNo', title: '客户货号', sort: true}
                ,{field:'productCname', title:'中文名称', sort : true}
                ,{field:'productEname', title:'英文名称', sort : true}
                ,{field: 'productCdesc', title: '中文描述', sort: true}
                ,{field: 'productEdesc', title: '英文描述', sort: true}
                ,{field:'productNum', title:'数量', sort : true,
                    templet: function(d){
                        let productNum = d.productNum?d.productNum:0;
                        return Number(productNum).toFixed(2)
                    }}
                ,{field:'productUnitCode', title:'单位', sort : true}
                ,{field:'productSurplusNum', title:'剩余数量', sort : true,
                    templet: function(d){
                        let productSurplusNum = d.productSurplusNum?d.productSurplusNum:0;
                        return Number(productSurplusNum).toFixed(2)
                    }}
                ,{field: 'unitPrice', title: '单价', sort : true,
                    templet: function(d){
                        let unitPrice = d.unitPrice?d.unitPrice:0;
                        return Number(unitPrice)
                    }}
                ,{field: 'moneySubtotal', width: 120, title: '金额小计', sort : true,
                    templet: function(d){
                        let moneySubtotal = d.moneySubtotal?d.moneySubtotal:0;
                        return Number(moneySubtotal).toFixed(2)
                    }}
            ]]
            ,id: 'producttableid'
           // ,limit:Number.MAX_VALUE
            ,height: 400
            ,done:function () {
                $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
            }
        });
        if(res.data.length != 0){
            var jsons = {"id":res.data[0].id,"changeList":[]}
            changeList.push(jsons);
        }
    }
});

//监听复选框
table.on('checkbox(mainstable)', function (data) {
    checkboxs = true;
    table.reload('producttableid', {
        method:'get'
        ,url:'exportContract/import/getContractProduct'
        ,where: {
            id:data.data.id  //res.data.length == 0 ? "":res.data[0].id //默认第一条信息，数据为空则id为空
        }
       // ,limit:Number.MAX_VALUE
        ,done: function (res, curr, count) {
            var shu = 0;
            for(var i = 0;i<changeList.length;i++){
                if(changeList[i].id == data.data.id){
                    indexs = i;
                    shu ++;
                }
            }
            if(shu == 0){
                var jsons = {"id":data.data.id,"changeList":[]};
                changeList.push(jsons);
                indexs = changeList.length-1;
            }
            var child = $("#product").next().find('tbody input[type="checkbox"]');
            child.each(function(index, item){
                item.checked = data.checked;
            });
            if(data.checked){　　　　　　//判断当前多选框是选中还是取消选中
                changeList[indexs].changeList = layui.table.cache["producttableid"];
            }else{
                changeList[indexs].changeList = [];
            }
            $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
            form.render('checkbox');
            layer.closeAll();    //返回数据关闭loading
        }
    }, 'data');
});

//监听复选框
table.on('checkbox(producttable)', function (obj) {
    var index = layer.load(1); //添加laoding
    //如果checked为false
    if (!obj.checked) {
        if(obj.type=="all"){
            changeList[indexs].changeList = [];
        }else{
            for (var i = 0; i < changeList[indexs].changeList.length; i++) {
                //如果数据中有这个数据就移除
                if (changeList[indexs].changeList[i].id == obj.data.id) {
                    changeList[indexs].changeList.splice(i, 1);
                }
            }
        }
    }else{
        if(obj.type=="all"){
            changeList[indexs].changeList = layui.table.cache["producttableid"];
        }else{
            //如果没有这个数据就加进去
            changeList[indexs].changeList.splice(changeList[indexs].changeList.length, 0, obj.data);
        }
    };

    var child = $("#mains").next().find('tbody tr');
    //input[type="checkbox"]
    var mainsdata = layui.table.cache["mainstableid"];
    child.each(function(index, item){
        var dataindex =  $(item).attr("data-index");
        if(mainsdata[dataindex].id == changeList[indexs].id && $(item).find('td input[type="checkbox"]')[0].checked != true){
            $(item).find('td input[type="checkbox"]')[0].checked = true;
        }
    });
    // form.render('checkbox');task/import/getTaskProductByPage
    table.reload('producttableid', {
        method:'get'
        ,url:'exportContract/import/getContractProduct'
        ,where: {
            id:changeList[indexs].id //默认第一条信息，数据为空则id为空
        }
      //  ,limit:Number.MAX_VALUE
        // data:data1
        //,where: changeList[indexs].id//点击行ID
        ,done: function (res, curr, count) {
            var subscript = [];
            for(var i = 0 ;i<res.data.length;i++){
                for(var j = 0;j<changeList[indexs].changeList.length;j++){
                    if(res.data[i].id == changeList[indexs].changeList[j].id){
                        var k = i;
                        subscript.push(k);
                    }
                }
            }
            var child = $("#product").next().find('tbody input[type="checkbox"]');
            child.each(function(index, item){
                var shul = 0;
                for(var i = 0 ;i<subscript.length;i++){
                    if(index == subscript[i]){
                        shul++;
                    }
                }
                if(shul == 0){
                    item.checked = false;
                }else{
                    item.checked = true;
                }
            });
            $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
            form.render('checkbox');
            layer.close(index);    //返回数据关闭loading
        }
    }, 'data');
});


form.on('submit(submitform)', function(data){
    table.reload('mainstableid', {
        url:"exportContract/import/getContractByPage"
        ,where: {
            "billNo":$("input[name='billNo']")[0].value,
            "customerContactNo":$("input[name='customerContactNo']")[0].value,
            "signingDateStart":$("input[name='signingDateStart']")[0].value,
            "signingDateEnd":$("input[name='signingDateEnd']")[0].value,
            "customerName":$("input[name='customerName']")[0].value,
            "isDeclare":$("select[name='isDeclare']")[0].value,
            "deptSalesmanCode":deptSalesmanList.getValue('valueStr').length>0?deptSalesmanList.getValue('valueStr'):user.code,
        }
        ,method:"get"
        ,page: {
            curr: 1 //重新从第 1 页开始
        }

    }, 'data');
    return false;
});

$("#choose").on("click",function () {
    var purchaseorderdata =   table.checkStatus("mainstableid").data; //第一个表格选中的数据

    if (purchaseorderdata.length>1){
        let businessModelCodeS=new Set();
        let customerCodeS=new Set();
        let currencyCodeS=new Set();
        let priceTermsCodeS=new Set();
        for(let i in purchaseorderdata){
            businessModelCodeS.add(purchaseorderdata[i].businessModelCode);
            customerCodeS.add(purchaseorderdata[i].customerCode);
            currencyCodeS.add(purchaseorderdata[i].currencyCode);
            priceTermsCodeS.add(purchaseorderdata[i].priceTermsCode);
        }
        if (businessModelCodeS.size>1){
            layer.msg("选择的多个合同业务模式不同，不能进行选择！");
            return false;
        }
        if (customerCodeS.size>1){
            layer.msg("选择的多个合同客户不同，不能进行选择！");
            return false;
        }
        if (currencyCodeS.size>1){
            layer.msg("选择的多个合同币种不同，不能进行选择！");
            return false;
        }
        if (priceTermsCodeS.size>1){
            layer.msg("选择的多个合同价格术语不同，不能进行选择！");
            return false;
        }

    }

    //判断是否已经在当彰计划中导入过,是否是同模式的合同
    if(isExit(purchaseorderdata[0].billNo,
        purchaseorderdata[0].businessModelCode,
        purchaseorderdata[0].customerCode,
        purchaseorderdata[0].currencyCode,
        purchaseorderdata[0].priceTermsCode)){
        return false;
    }

    //新数组里的id集合，用来和父页面的外销id比较
    let ids=[];
    for(let i=0;i<changeList.length;i++){
        let productList=changeList[i].changeList;
        for (let n in productList) {
            ids.push(productList[n].id);
        }
    }

    let productList=parent.productList;

    //去处重复值
    for (let n in changeList) {
        for (let i in productList) {
            //有重复值
            if(ids.indexOf(productList[i].productId)!=-1){
                //去掉重复值，并返回新数组
                let newChangeArray=changeList[n].changeList.filter((item) => item.id != productList[i].productId)
                changeList[n].changeList=[];//清空
                changeList[n].changeList=newChangeArray;//赋值
            }
        }
    }

    parent.wxandbhflag2("w");
    parent.cyjhreshWX(purchaseorderdata,changeList);//将两个表格中选择的数据传递给父对象
    setTimeout(function () {
        //保存成功则关闭此页面
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    },1000);
    /*if(purchaseorderdata.length + changeList.length == 0){
        layer.msg("请选择数据")
    }else{
        //执行接口
        layer.msg("保存成功", {icon: 6});

    }*/
})
//判断是否已经在当彰计划中导入过
function isExit(billNo,businessModelCode,customerCode,currencyCode,priceTermsCode){
    var flag=false;
    if(parent.businessMode !="" &&parent.businessMode != businessModelCode){
        layer.msg("此合同业务模式与当前计划中的合同不是同种业务模式，不能进行导入！");
        flag=true;
        return  flag;
    }

    if(parent.parentCustomerCode !="" &&parent.parentCustomerCode != customerCode){
        layer.msg("此合同客户与当前计划中的合同不是同一个客户，不能进行导入！");
        flag=true;
        return  flag;
    }
    if(parent.parentCurrencyCode !="" &&parent.parentCurrencyCode != currencyCode){
        layer.msg("此合同币种与当前计划中的合同不是同一个币种，不能进行导入！");
        flag=true;
        return  flag;
    }
    if(parent.parentPriceTermsCode !="" &&parent.parentPriceTermsCode != priceTermsCode){
        layer.msg("此合同价格术语与当前计划中的合同不是同一个价格术语，不能进行导入！");
        flag=true;
        return  flag;
    }

    return flag;
}
$("#shutdown").on("click",function () {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
})
document.getElementById('clear').onclick = function(){
    deptSalesmanList.setValue([ ]);
};